package com.dminvoicemanager.reports;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_Reports_Generator;
import com.dminvoicemanager.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_Sales_Summary_Report_SI extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	private String USER_SETTINGS = "usersettings";
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", item_result_8 = "0", item_result_9 = "0",
			item_result_13 = "0", item_result_17 = "0", item_result_10,
			item_result_18, PrintGrandTot, item_result_11;

	int item_result_tot_2 = 0, item_result_tot_3 = 0, item_result_tot_4 = 0,
			item_result_tot_5 = 0, item_result_tot_6 = 0,
			item_result_tot_7 = 0, item_result_tot_8 = 0,
			item_result_tot_9 = 0, PrintGrandTot_tot = 0,
			item_result_17Val = 0, item_result_18Val = 0;
	double item_result_tot_10 = 0.0, item_result_tot_13 = 0.0,
			invoice_sales_tot = 0.0, invoice_tonage_sales_tot = 0.0;

	int toDayTag = 0;
	DecimalFormat numberFormat = new DecimalFormat("#.000000");
	DecimalFormat numberFormatAmt = new DecimalFormat("#,###,###.00");

	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname;
	TextView txtHeadingReports, totalSum, totalTonage;
	TextView recordtot_1, recordtot_2, recordtot_3, recordtot_4, recordtot_5,
			recordtot_6, recordtot_7, recordtot_8, recordtot_9, recordtot_10,
			recordtot_11, recordtot_12;

	String currentReportName, selectFromDate, selectToDate, currentUserTemp,
			currentUserPrefix, UserLocCode, selectFromDateNow, selectToDateNow;

	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	double totalValueSum = 0;

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "RID/RNAME");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_sales_summary_report_siso);

		Bundle bundle = getIntent().getExtras();

		currentReportName = bundle.getString("REPORTNAME");
		selectFromDate = bundle.getString("FROMDATE");
		selectToDate = bundle.getString("TODATE");

		if (selectFromDate.equals(selectToDate)) {
			selectFromDateNow = selectFromDate.toString().trim();
			Log.v(TAG, "selectFromDateNow onCreate:" + selectFromDateNow);
			toDayTag = 33;
		} else {
			try {
				selectFromDateNow = selectFromDate.toString().trim();
				date = originalFormat.parse(selectFromDate.replaceAll(
						"[-+/.^:,]", " "));
				Log.v(TAG, "Old Format From:" + originalFormat.format(date));
				Log.v(TAG, "New Format From:" + targetFormat.format(date));
				selectFromDate = targetFormat.format(date);
				LoadingFromDate = (Date) targetFormat.parse(selectFromDate);

			} catch (ParseException ex) {

			}

			try {
				selectToDateNow = selectToDate.toString().trim();
				date = originalFormat.parse(selectToDate.replaceAll(
						"[-+/.^:,]", " "));
				Log.v(TAG, "Old Format To:" + originalFormat.format(date));
				Log.v(TAG, "New Format To:" + targetFormat.format(date));
				selectToDate = targetFormat.format(date);
				LoadingToDate = (Date) targetFormat.parse(selectToDate);

			} catch (ParseException ex) {

			}

		}

		Log.v(TAG, "F DATE :" + selectFromDate);
		Log.v(TAG, "T DATE :" + selectToDate);
		txtHeadingReports = (TextView) findViewById(R.id.txtHeadingReports);
		txtHeadingReports.setText(currentReportName);
		dmreportfromdate = (EditText) findViewById(R.id.dmreportfromdate);
		dmreportfromdate.setText(selectFromDate);
		dmreporttodate = (EditText) findViewById(R.id.dmreporttodate);
		dmreporttodate.setText(selectToDate);
		dmdisplayrepname = (EditText) findViewById(R.id.dmdisplayrepname);
		totalSum = (TextView) findViewById(R.id.totalSum);

		currentuserTemp();
		// create the grid item mapping

		showCurrentInvoiceItemsLoading();
		// showDailySalesSummary();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					dmdisplayrepname.setText(currentUserTemp);
				}
			}
		}
		selectCurrentuserrec.close();
		mydb.close();
	}

	private void showCurrentInvoiceItemsLoading() {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3", "item_result_4", "item_result_5",
				"item_result_6", "item_result_7", "item_result_8",
				"item_result_9", "item_result_10", "item_result_13" };

		int[] totrdes = new int[] { R.id.item_name, R.id.record_1,
				R.id.record_2, R.id.record_3, R.id.record_4, R.id.record_5,
				R.id.record_6, R.id.record_7, R.id.record_8, R.id.record_9,
				R.id.record_12 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;
		String columsup[] = { "refInvoiceDetCode" };
		// String FromDate = "2013-10-21", ToDate = "2013-10-22";
		Log.v(TAG, "TO DATE Summary:" + selectToDate.trim());

		// selectFromDateNow = "17/02/2014"; //selectFromDateNow.trim(); //
		// selectFromDateNow = selectFromDateNow.trim(); //"11/02/2014";
		// selectToDateNow = selectToDateNow.trim(); //"12/02/2014";
		String query;
		try {
			if (toDayTag == 33) {
				query = "SELECT FD.Itemcode,itemDescription,sum(case when TxnType = 22 then CaseQty else 0 end),sum(case when TxnType = 25 then CaseQty else 0 end),sum(case when TxnType = 27 then CaseQty else 0 end) ,sum(case when TxnType = 31 then CaseQty else 0 end),sum(case when TxnType = 22 then PiceQty else 0 end),sum(case when TxnType = 25 then PiceQty else 0 end) ,sum(case when TxnType = 27 then PiceQty else 0 end),sum(case when TxnType = 31 then PiceQty else 0 end),sum(case when TxnType = 22 then Amt else 0 end),(FS.Tonnage),sum(case when TxnType = 22 then Qty else 0 end),(fS.Tonnage * sum(case when FD.TxnType = 22 then Qty else 0 end)) ,ISUM.invoiceComplete ,ISUM.invoiceRef, FD.RefNo, FD.refInvitemCaseQty, FD.itemUnitPrice from FinvDet as FD,fItems as FI, FSKU as FS, frepInvoiceSumery as ISUM  Where TxnDate = '"
						+ selectFromDateNow.trim()
						+ "' AND FI.SKUCode = FS.SKUCode AND FD.Itemcode = FI.ItemCode AND ISUM.invoiceRef = FD.RefNo AND FD.invdetSync <> 3 AND ISUM.invoiceComplete = '2'  group by FD.Itemcode,FS.Tonnage";
			} else {
				query = "SELECT FD.Itemcode,itemDescription,sum(case when FD.TxnType = 22 then CaseQty else 0 end),sum(case when FD.TxnType = 25 then CaseQty else 0 end),sum(case when FD.TxnType = 27 then CaseQty else 0 end) ,sum(case when FD.TxnType = 31 then CaseQty else 0 end),sum(case when FD.TxnType = 22 then PiceQty else 0 end),sum(case when FD.TxnType = 25 then PiceQty else 0 end) ,sum(case when FD.TxnType = 27 then PiceQty else 0 end),sum(case when FD.TxnType = 31 then PiceQty else 0 end),sum(case when FD.TxnType = 22 then Amt else 0 end),(FS.Tonnage),sum(case when FD.TxnType = 22 then Qty else 0 end),(fS.Tonnage * sum(case when FD.TxnType = 22 then Qty else 0 end)),ISUM.invoiceComplete ,ISUM.invoiceRef, FD.RefNo, FD.refInvitemCaseQty, FD.itemUnitPrice from FinvDet as FD,fItems as FI, FSKU as FS, frepInvoiceSumery as ISUM  Where fd.txndate between '"
						+ selectFromDateNow.trim()
						+ "' AND '"
						+ selectToDateNow.trim()
						+ "' AND FI.SKUCode = FS.SKUCode AND FD.Itemcode = FI.ItemCode AND ISUM.invoiceRef = FD.RefNo AND FD.invdetSync <> 3 AND ISUM.invoiceComplete = '2' group by FD.Itemcode,FS.Tonnage";
			}

			// ***Select sum queries need seperately 8 to for the combinations
			allrowitemsdes = mydb.rawQuery(query, null);
			Log.v(TAG, "Count:" + allrowitemsdes.getCount());
			if (allrowitemsdes != null) {
				if (allrowitemsdes.getCount() > 0) {
					while (allrowitemsdes.moveToNext()) {

						String rawAmount = allrowitemsdes.getString(10);
						double rawAmountVal = Double.parseDouble(rawAmount
								.replaceAll("[,]", ""));
						totalValueSum = totalValueSum + rawAmountVal;

						PrintGrandTot = Double.toString(totalValueSum);
						// itemDescription
						item_result_1 = allrowitemsdes.getString(1);
						// Case Qty sales 22 SA
						item_result_2 = allrowitemsdes.getString(2);
						int item_result_2Val = Integer.parseInt(item_result_2
								.replaceAll("[,]", ""));
						item_result_tot_2 = item_result_tot_2
								+ item_result_2Val;

						// Case Qty ureturn 25 UR
						item_result_3 = allrowitemsdes.getString(3);
						int item_result_3Val = Integer.parseInt(item_result_3
								.replaceAll("[,]", ""));
						item_result_tot_3 = item_result_tot_3
								+ item_result_3Val;

						// Case Qty fissue 27 FI
						item_result_4 = allrowitemsdes.getString(4);
						int item_result_4Val = Integer.parseInt(item_result_4
								.replaceAll("[,]", ""));
						item_result_tot_4 = item_result_tot_4
								+ item_result_4Val;

						// Case Qty mreturn 31 MR
						item_result_5 = allrowitemsdes.getString(5);
						int item_result_5Val = Integer.parseInt(item_result_5
								.replaceAll("[,]", ""));
						item_result_tot_5 = item_result_tot_5
								+ item_result_5Val;

						// PictotalValueSumes Qty sales 22 SA
						item_result_6 = allrowitemsdes.getString(6);
						int item_result_6Val = Integer.parseInt(item_result_6
								.replaceAll("[,]", ""));
						item_result_tot_6 = item_result_tot_6
								+ item_result_6Val;

						// Pices Qty ureturn 25 UR
						item_result_7 = allrowitemsdes.getString(7);
						int item_result_7Val = Integer.parseInt(item_result_7
								.replaceAll("[,]", ""));
						item_result_tot_7 = item_result_tot_7
								+ item_result_7Val;

						// Pices Qty fissue 27 FI
						item_result_8 = allrowitemsdes.getString(8);
						int item_result_8Val = Integer.parseInt(item_result_8
								.replaceAll("[,]", ""));
						item_result_tot_8 = item_result_tot_8
								+ item_result_8Val;

						// Pices Qty mreturn 31 MR
						item_result_9 = allrowitemsdes.getString(9);
						int item_result_9Val = Integer.parseInt(item_result_9
								.replaceAll("[,]", ""));
						item_result_tot_9 = item_result_tot_9
								+ item_result_9Val;

						// Amt
						item_result_10 = allrowitemsdes.getString(10);
						double item_result_10Val = Double
								.parseDouble(item_result_10.replaceAll("[,]",
										""));
						String Stritem_result_10Val = numberFormatAmt
								.format(item_result_10Val);
						item_result_tot_10 = item_result_tot_10
								+ item_result_10Val;

						// tonage for one item
						item_result_11 = allrowitemsdes.getString(11);
						double item_result_11Val = Double
								.parseDouble(item_result_11.replaceAll("[,]",
										""));

						// tonage
						item_result_13 = allrowitemsdes.getString(13);
						double item_result_13Val = Double
								.parseDouble(item_result_13.replaceAll("[,]",
										""));
						String Stritem_result_13Val = numberFormat
								.format(item_result_13Val);
						item_result_tot_13 = item_result_tot_13
								+ item_result_13Val;

						// Seleted Item Case Quantity
						item_result_17 = allrowitemsdes.getString(17);
						item_result_17Val = Integer.parseInt(item_result_17
								.replaceAll("[,]", ""));

						// Seleted Item price Quantity
						item_result_18 = allrowitemsdes.getString(18);
						double item_result_18Val = Double
								.parseDouble(item_result_18.replaceAll("[,]",
										""));

						// Calculate Sales (SA - UR)
						// Cases(SA)
						int item_result_2Val_pie = (item_result_2Val * item_result_17Val)
								+ item_result_6Val;
						// Cases(UR)
						int item_result_3Val_pie = (item_result_3Val * item_result_17Val)
								+ item_result_7Val;
						// Pieces (SA) - Pieces (UR)
						int net_sales_pieces = item_result_2Val_pie
								- item_result_3Val_pie;

						// Calculate Net Total For Item
						double net_value_items = item_result_18Val
								* (double) net_sales_pieces;
						invoice_sales_tot = invoice_sales_tot + net_value_items;
						String Strnet_value_itemsVal = numberFormatAmt
								.format(net_value_items);

						// Calculate Net Tonage For Item
						double net_tonage_value_items = item_result_11Val
								* (double) net_sales_pieces;
						invoice_tonage_sales_tot = invoice_tonage_sales_tot
								+ net_tonage_value_items;
						String Strnet_tonage_value_itemsVal = numberFormat
								.format(net_tonage_value_items);

						// Convert back to Cases /Pieces
						int net_sales_cases = net_sales_pieces
								/ item_result_17Val;
						net_sales_pieces = net_sales_pieces
								- (net_sales_cases * item_result_17Val);

						String Strnet_sales_cases = Integer
								.toString(net_sales_cases);
						String Strnet_sales_pieces = Integer
								.toString(net_sales_pieces);

						if (Strnet_sales_cases.equals("0")
								&& Strnet_sales_pieces.equals("0")) {

						} else {
							HashMap<String, String> maptrdes = new HashMap<String, String>();
							maptrdes.put("item_result_1", item_result_1);
							// print Case Qty sales 22 SA
							maptrdes.put("item_result_2", Strnet_sales_cases);
							// print Pices Qty sales 22 SA
							maptrdes.put("item_result_3", Strnet_sales_pieces);
							// print Case Qty ureturn 25 UR
							maptrdes.put("item_result_4", item_result_3);
							// print Pices Qty ureturn 25 UR
							maptrdes.put("item_result_5", item_result_7);
							// print Case Qty mreturn 31 MR
							maptrdes.put("item_result_8", item_result_4);
							// print Pices Qty mreturn 31 MR
							maptrdes.put("item_result_9", item_result_8);
							// print Case Qty fissue 27 FI
							maptrdes.put("item_result_6", item_result_5);
							// print Pices Qty fissue 27 FI
							maptrdes.put("item_result_7", item_result_9);
							// Amt
							maptrdes.put("item_result_10",
									Strnet_value_itemsVal);
							// Tonage
							maptrdes.put("item_result_13",
									Strnet_tonage_value_itemsVal);

							// fill in the grid_item layout
							fillMapstrdes.add(maptrdes);
							SimpleAdapter adaptertrdes = new SimpleAdapter(
									this, fillMapstrdes,
									R.layout.dm_sales_summary_report_raw_siso,
									fromtrdes, totrdes);
							lvtypedes.setAdapter(adaptertrdes);
						}
					}

				}

				// printing Final Values
				HashMap<String, String> maptrdes = new HashMap<String, String>();

				maptrdes.put("item_result_1", "Grand Total");

				// Pre calculate Cases and Pieces(SA)
				int total_inv_cases_Pieces = item_result_tot_2
						* item_result_17Val;
				int total_sales_pieces = total_inv_cases_Pieces
						+ item_result_tot_6;
				// Pre calculate Cases and Pieces(UR)
				int total_inv_cases_Pieces_ur = item_result_tot_3
						* item_result_17Val;
				int total_sales_pieces_ur = total_inv_cases_Pieces_ur
						+ item_result_tot_7;
				// Pre net sales for invoices
				int net_sales_items_inv = total_sales_pieces
						- total_sales_pieces_ur;

				int net_sales_items_inv_cs = net_sales_items_inv
						/ item_result_17Val;
				int net_sales_items_inv_pi = net_sales_items_inv
						- (net_sales_items_inv_cs * item_result_17Val);

				// print Case Qty sales 22 SA
				String item_result_totval_2 = Integer
						.toString(net_sales_items_inv_cs);
				maptrdes.put("item_result_2", item_result_totval_2);

				// print Pices Qty sales 22 SA
				String item_result_totval_6 = Integer
						.toString(net_sales_items_inv_pi);
				maptrdes.put("item_result_3", item_result_totval_6);

				// print Case Qty ureturn 25 UR
				String item_result_totval_3 = Integer
						.toString(item_result_tot_3);
				maptrdes.put("item_result_4", item_result_totval_3);

				// print Pices Qty ureturn 25 UR
				String item_result_totval_7 = Integer
						.toString(item_result_tot_7);
				maptrdes.put("item_result_5", item_result_totval_7);

				// print Case Qty mreturn 31 MR
				String item_result_totval_4 = Integer
						.toString(item_result_tot_4);
				maptrdes.put("item_result_8", item_result_totval_4);

				// print Pices Qty mreturn 31 MR
				String item_result_totval_8 = Integer
						.toString(item_result_tot_8);
				maptrdes.put("item_result_9", item_result_totval_8);

				// print Case Qty fissue 27 FI
				String item_result_totval_5 = Integer
						.toString(item_result_tot_5);
				maptrdes.put("item_result_6", item_result_totval_5);

				// print Pices Qty fissue 27 FI
				String item_result_totval_9 = Integer
						.toString(item_result_tot_9);
				maptrdes.put("item_result_7", item_result_totval_9);

				// Amt
				String Strnet_value_itemsVal = numberFormatAmt
						.format(invoice_sales_tot);
				maptrdes.put("item_result_10", Strnet_value_itemsVal);

				// Tonage
				String Strnet_tonage_value_itemsVal = numberFormat
						.format(invoice_tonage_sales_tot);
				maptrdes.put("item_result_13", Strnet_tonage_value_itemsVal);

				// fill in the grid_item layout
				fillMapstrdes.add(maptrdes);
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_sales_summary_report_raw_siso, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);

				totalSum.setText(PrintGrandTot);
			}
			allrowitemsdes.close();
			mydb.close();
		} catch (Exception e) {
		}

	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
